import { createCanvas } from 'canvas'
function randomChar() {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz2345678923456789';
  return chars[Math.floor(Math.random() * chars.length)];
}
function randomColor(maxBrightness = 200): string {
  const r = Math.floor(Math.random() * maxBrightness);
  const g = Math.floor(Math.random() * maxBrightness);
  const b = Math.floor(Math.random() * maxBrightness);
  return `rgb(${r},${g},${b})`;
}
function drawLine(ctx: any, fromX: number, fromY: number, toX: number, toY: number, color: string) {
  ctx.beginPath();
  ctx.moveTo(fromX, fromY);
  ctx.lineTo(toX, toY);
  ctx.strokeStyle = color;
  ctx.lineWidth = 1;
  ctx.stroke();
}
function drawNoise(ctx: any, num: number) {
  for (let i = 0; i < num * 2; i++) {
    drawLine(ctx,
      Math.random() * ctx.canvas.width,
      Math.random() * ctx.canvas.height,
      Math.random() * ctx.canvas.width,
      Math.random() * ctx.canvas.height,
      randomColor());
  }
  for (let i = 0; i < num; i++) {
    ctx.fillStyle = randomColor();
    ctx.fillRect(Math.random() * ctx.canvas.width, Math.random() * ctx.canvas.height, 1, 1);
  }
}
function create(width = 85, height = 35, fontSize = 30, noiseNum = 4) {
  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext('2d')!;
  ctx.fillStyle = 'transparent';
  ctx.fillRect(0, 0, width, height);
  const fontWeight = Math.random() > 0.5 ? 'bold' : 'normal';
  ctx.font = `${fontWeight} ${fontSize}px Arial`;
  ctx.textBaseline = 'middle';
  const captchaText = Array.from({ length: 4 }, () => randomChar()).join('');
  for (let i = 0; i < captchaText.length; i++) {
    ctx.fillStyle = randomColor();
    ctx.translate(18 * i + 5, 15);
    ctx.rotate((Math.random() - 0.5) * 0.1);
    ctx.fillText(captchaText[i], 0, 0);
    ctx.rotate(-(Math.random() - 0.5) * 0.1);
    ctx.translate(-(18 * i + 5), -15);
  }
  drawNoise(ctx, noiseNum);
  const buffer = canvas.toBuffer('image/png').toString('base64')
  const data = `data:image/png;base64,${buffer}`;
  return { data, text: captchaText.toLocaleLowerCase() };
}

export default create